<script setup>
import { ref, computed, defineEmits } from 'vue'
import { useStore } from 'vuex'
import dateFormater from '@/utils/dateFormater'
import { messageType } from '@/constant'
import _ from 'lodash'
import { useRouter, useRoute } from 'vue-router'
/* 头像相关 */
import informIcon from '@/assets/images/avatar/inform.png'
/* route */
const route = useRoute()
/* router */
const router = useRouter()
/* store */
const store = useStore()
const { CHAT_TYPE } = messageType
//登录用户ID
const loginUserId = computed(() => store.state.loginUserInfo.hxId)
//取系统通知数据
const informDetail = computed(() => {
    const informDetailArr = store.state.Conversation.informDetail
    const lastInformDeatail = informDetailArr[0] || {}
    const untreated = _.sumBy(informDetailArr, 'untreated') || 0
    return { untreated, lastInformDeatail }
})
// console.log('>>>>>informDetail', informDetail.lastInformDeatail)
//取好友列表(主要使用好友下的用户属性相关)
const friendList = computed(() => store.state.Contacts.friendList)

//取群组列表（展示群组名称）
const joinedGroupList = computed(() => store.state.Contacts.groupList)

//取会话数据
const conversationList = computed(() => {
    return store.state.Conversation.conversationListData
})

//处理会话name
const handleConversationName = computed(() => {
    return (item) => {
        if (item.conversationType === CHAT_TYPE.SINGLE) {
            const friend = friendList.value[item.conversationKey]
            return friend?.nickname || item.conversationInfo.name
        }
        if (item.conversationType === CHAT_TYPE.GROUP) {
            const group = joinedGroupList.value[item.conversationKey]
            if (group?.groupDetail) {
                return group.groupDetail.name
            } else if (group?.groupname) {
                return group.groupname
            }
        }
        return item.conversationKey
    }
})
//处理lastmsg的from昵称
const handleLastMsgNickName = computed(() => {
    const friendList = store.state.Contacts.friendList
    const groupsInfos = store.state.Groups.groupsInfos
    return (conversation) => {
        const {
            conversationKey: groupId,
            conversationType,
            fromInfo
        } = conversation
        const { fromId } = fromInfo || {}
        if (conversationType === CHAT_TYPE.GROUP) {
            const userInfoFromGroupNickname =
                groupsInfos[groupId]?.groupMemberInfo?.[fromId]?.nickName
            const friendUserInfoNickname = friendList[fromId]?.nickname
            return `${
                userInfoFromGroupNickname || friendUserInfoNickname || fromId
            }：`
        }
    }
})
//取网络状态
const networkStatus = computed(() => {
    return store.state.networkStatus
})

const emit = defineEmits(['toInformDetails', 'toChatMessage'])
//普通会话
const checkedConverItemIndex = ref(null)
const toChatMessage = (item, itemKey, index) => {
    checkedConverItemIndex.value = index
    if (item && item.unreadMessageNum > 0)
        store.commit('CLEAR_UNREAD_NUM', itemKey)
    if (item.isMention) store.commit('CLEAR_AT_STATUS', itemKey)
    //跳转至对应的消息界面

    emit('toChatMessage', itemKey, item.conversationType)
}
//删除某条会话
const deleteConversation = (itemKey) => {
    console.log('选中的会话key', itemKey, route.query)
    store.commit('DELETE_ONE_CONVERSATION', itemKey)
    //如果删除的itemKey与当前的message会话页的id一致则跳转至会话默认页。
    if (route?.query?.id && route.query.id === itemKey) {
        router.push('/conversation')
    }
}
//加载到底拉取新数据
// const load = () => {
//   console.log('>>>>>加载到底');
// };
</script>
<template>
  <el-scrollbar class="session_list fill_div" style="overflow: auto" tag="ul">
    <li class="offline_hint f_center" v-if="!networkStatus">
      <span class="plaint_icon">!</span> 网络不给力，请检查网络设置。
    </li>
    <!-- 系统通知会话 v-if="JSON.stringify(informDetail.lastInformDeatail) !== '{}' &&informDetail.untreated >= 1"  -->
    <li class="session_list_item_h5 flex_row f_a_center gap_20px padding_20px" v-if="JSON.stringify(informDetail.lastInformDeatail) !== '{}' &&informDetail.untreated >= 1" @click="$emit('toInformDetails')">
      <!-- 通知头像 -->
      <div class="flex_1 flex_row f_a_center gap_20px">
        <div class="session_other_avatar">
          <el-avatar :size="64" :src="informIcon" />
        </div>
        <div class="item_body ">
          <div class="name">系统通知</div>
          <span>
            {{ informDetail.lastInformDeatail.from }}
            :
            {{informDetail.lastInformDeatail.desc}}
          </span>
        </div>
      </div>
      <div class="item_body fill_height flex_row gap_20px flex_shrink">
        <span class="time">
          {{
            dateFormater(
                'MM/DD/HH:mm',
                informDetail.lastInformDeatail.time
            )
                }}
        </span>
        <span class="unReadNum_box">
          <sup class="unReadNum_count " v-text="
                           informDetail.untreated >= 99
                                ? '99+'
                                : informDetail.untreated
                        "></sup>
        </span>
      </div>
    </li>
    <!-- 普通会话 -->
    <template v-if="Object.keys(conversationList).length > 0">
      <li v-for="(item, itemKey, index) in conversationList" :key="itemKey" @click="toChatMessage(item, itemKey, index)" :style="{
                    background:
                        checkedConverItemIndex === index ? '#E5E5E5' : ''
                }">
        <el-popover popper-class="conversation_popover" placement="right-end" trigger="contextmenu" :show-arrow="false" :offset="-10">
          <template #reference>
            <div class="session_list_item_h5 flex_row f_a_center gap_20px padding_20px">
              <div class="flex_1 flex_row f_a_center gap_20px">
                <el-avatar :size="64" :src="
                                            friendList[item.conversationKey] &&
                                            friendList[item.conversationKey]
                                                .avatarurl
                                                ? friendList[
                                                      item.conversationKey
                                                  ].avatarurl
                                                : item.conversationInfo
                                                      .avatarUrl
                                        ">
                </el-avatar>
                <div class="item_body item_main">
                  <div class="name">
                    {{ handleConversationName(item) }}
                  </div>
                  <div class="last_msg_body" style="color:#333;">
                    <span class="last_msg_body_mention" v-if="item.isMention">[有人@我]</span>
                    <span  v-show="
                                            item.conversationType ===
                                            CHAT_TYPE.GROUP
                                        ">{{ handleLastMsgNickName(item) }}</span>
                    {{ item.latestMessage.msg }}
                  </div>
                </div>
              </div>
              <div class="item_body item_right">
                <span class="time">{{
                                    dateFormater(
                                        'MM/DD/HH:mm',
                                        item.latestSendTime
                                    )
                                }}</span>
                <span class="unReadNum_box" v-if="item.unreadMessageNum >= 1">
                  <sup class="unReadNum_count" v-text="
                                            item.unreadMessageNum >= 99
                                                ? '99+'
                                                : item.unreadMessageNum
                                        "></sup>
                </span>
              </div>
            </div>
          </template>
          <template #default>
            <div class="session_list_delete" @click="deleteConversation(itemKey)">
              删除会话
            </div>
          </template>
        </el-popover>
      </li>
    </template>
    <template v-else>
      <el-empty description="暂无最近会话" />
    </template>
  </el-scrollbar>
</template>

<style lang="scss" scoped>
.session_list {
    position: relative;
    padding: 0;
    margin: 0;
    font-size: 50px;
    .offline_hint {
        min-height: 100px;
        height: auto;
        text-align: center;
        color: #f35f81;
        background: #fce7e8;

        .plaint_icon {
            width: 50px;
            height: 50px;
            display: inline-block;
            color: #e5e5e5;
            background: #e6686e;
            border-radius: 50%;
        }
    }
    .session_list_item_h5 {
        background: #f0f0f0;
        color: var(--el-color-primary);
        border-bottom: 1px solid var(--el-border-color);
        cursor: pointer;
        &:hover {
            background: #e5e5e5;
        }

        .item_body {
            span {
                font-size: 35px;
                color: #a3a3a3;
            }
            .time {
            }

            .unReadNum_box {
                margin-top: 10px;
                vertical-align: middle;
                .unReadNum_count {
                    display: inline-block;
                    min-width: 80px;
                    height: 60px;
                    padding: 0 20px;
                    color: #fff;
                    font-weight: normal;
                    font-size: 40px;
                    line-height: 60px;
                    white-space: nowrap;
                    text-align: center;
                    background: #f5222d;
                    border-radius: 20px;
                    box-sizing: border-box;
                }
            }
        }
    }
}

.session_list_item_active {
    background: #d2d2d2;
}

.session_list .session_list_item_h5 + .list_item {
    margin-top: 10px;
}

.session_list_delete {
    cursor: pointer;
    transition: all 0.5s;

    &:hover {
        background: #e1e1e1;
    }
}
</style>
